/**    
 * @Description: 博客园地址：https://www.cnblogs.com/zumengjie/      
 * @author: 顶风少年   
 * @date: 2021年4月9日 上午10:35:01
 */

package datang.dtdb.executor.statement;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import datang.dtdb.exceptions.StatementException;
import datang.dtdb.executor.Executor;
import datang.dtdb.executor.RowBounds;
import datang.dtdb.mapping.BoundSql;
import datang.dtdb.mapping.MappedStatement;
import datang.dtdb.session.ResultHandler;

/**
 * 对应jdbc中的preparedStatement
 */
public class PreparedStatementHandler extends BaseStatementHandler {

	public PreparedStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameter,
			RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
		super(executor, mappedStatement, parameter, rowBounds, resultHandler, boundSql);
	}

	/**
	 * 修改，删除，新增
	 * */
	@Override
	public int update(Statement statement) {
		PreparedStatement preparedStatement =(PreparedStatement) statement;
		try {
			return preparedStatement.executeUpdate();
		} catch (SQLException e) {
			throw new StatementException("PreparedStatementHandler.update失败", e);
		}
	
	}

	/**
	 * 查询
	 */
	@Override
	public <E> List<E> query(Statement statement, ResultHandler resultHandler) {
		PreparedStatement preparedStatement =(PreparedStatement) statement;
		try {
			preparedStatement.executeQuery();
		} catch (SQLException e) {
			throw new StatementException("PreparedStatementHandler.query失败", e);
		}
		return resultSetHandler.handleResultSets(mappedStatement, statement);
	}

	/**
	 * 创建statement
	 */
	@Override
	protected Statement instantiateStatement(Connection connection) {
		Statement statement;
		try {
			statement = connection.prepareStatement(boundSql.getSql());
		} catch (SQLException e) {
			throw new StatementException("创建statement异常", e);
		}
		return statement;
	}

	/**
	 * 使用ParameterStatementHandler设置？参数
	 */
	@Override
	public void parameterize(Statement statement) {
		parameterHandler.setParameters((PreparedStatement) statement, parameter);
	}

}
